package es.truscoandrisco.discotecasmadrid;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class Actualizaciones extends ListActivity{

	private static ArrayList<Evento> arrayEventos = new ArrayList<Evento>();
	static Drawable[] arrayLogos = new Drawable[50];
	static boolean visitedLogos[] = new boolean[50];
	public static MyAdapter mAdapter = null;
	public static View localView;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{
        super.onCreate(savedInstanceState);        
        for (int i = 0; i < 50; i++){
        	visitedLogos[i] = false;
        }
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Aviso").setMessage("Los flyers que aquí se muestran tienen carácter informativo")
		       .setCancelable(false)
		       .setNegativeButton("Aceptar", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		                new getImageTask().execute();
		           }
		       }).show();
        
        mAdapter = new MyAdapter(this);
		setListAdapter(mAdapter);
		
		registerForContextMenu(getListView());
     
	}

	 protected void onListItemClick(ListView l, View v, int position, long id){

			    Intent i = new Intent(this, EventoActivity.class);
			    
			    i.putExtra("DISCOTECA", arrayEventos.get(position-1).getDisco());
				i.putExtra("DESCRIPCION", arrayEventos.get(position-1).getDescripcion());
				i.putExtra("FECHA", arrayEventos.get(position-1).getFecha());
				i.putExtra("ID", arrayEventos.get(position-1).getID());

				startActivity(i);
		}

	 
		public class MyAdapter extends BaseAdapter {
			
	        //Creamos la clase adaptador
			private Context mContext;

			public MyAdapter(Context c) {
				mContext = c;
			}

			//@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return arrayEventos.size()+1;
			}

			public Object getItem(int arg0) {
				// TODO Auto-generated method stub
				return null;
			}

			public long getItemId(int arg0) {
				// TODO Auto-generated method stub
				return 0;
			}
			
			public View getView(int position, View convertView, ViewGroup parent){
				
				View view;
				LayoutInflater inflater;
				
				if (position == 0){
					inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.myfirstitem, null);
					Button act = (Button) view.findViewById(R.id.act);
					
					act.setText("Actualizar");
					
					act.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							refreshList();
						}
					});
					
				}else{
					inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.itemevento, null);		
		
					
					ImageView imgv = (ImageView) view.findViewById(R.id.image);
					
					if (visitedLogos[position-1] == false){
						new downloadIcon().execute(position-1);
						visitedLogos[position-1] = true;
					}else{
						imgv.setImageDrawable(arrayLogos[position-1]);
					}
					
							
					TextView t = (TextView) view.findViewById(R.id.title);
					t.setText(arrayEventos.get(position-1).getDisco());
					
					t = (TextView) view.findViewById(R.id.evento);
					t.setText(arrayEventos.get(position-1).getDescripcion());
					
					t = (TextView) view.findViewById(R.id.fecha);
					t.setText(arrayEventos.get(position-1).getFecha());
					
					return view;
				}
				
				return view;
		
			}
	}
	
			
	private class getImageTask extends AsyncTask<Void, Void, Void>{
		
		ProgressDialog pd;
		
		protected void onPreExecute(){
			pd = ProgressDialog.show(Actualizaciones.this, "Por favor espere...",
										"Cargando lista de eventos...", true);
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			MyJSONEventos mjp = new MyJSONEventos();
	        String str = mjp.doGet("http://...");
	        arrayEventos = mjp.parse(str);
		
			return null;
		}
		
		protected void onPostExecute(Void unused){
			if (!isFinishing()){
				pd.dismiss();
				mAdapter.notifyDataSetChanged();
			}
		}
	
	}
	
	public static void launchDownloadIcon(int position) {
		new downloadIcon().execute(position);
	}
	
	private static class downloadIcon extends AsyncTask<Integer, Void, Void> {

		@Override
		protected Void doInBackground(Integer... params) {
			Integer position = params[0];
			
			if ((arrayEventos != null) && (arrayEventos.size() > position)){ 	

				String url = "http://..." + arrayEventos.get(position).getDisco() + "...jpg";
				
				try {
					arrayLogos[position] = arrayEventos.get(position).setLogo(url, "");
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			return null;
		}
		
		protected void onPostExecute(Void unused) {			
			mAdapter.notifyDataSetChanged();
		}    
	
	}
	
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.Actualizar:
        	refreshList();
            return true;
        case R.id.about:
        	Intent i = new Intent(this, About.class);
        	startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
	public void refreshList() {
        
		for (int i = 0; i < 50; i++){
        	visitedLogos[i] = false;
        }
        
		new getImageTask().execute();
			
		mAdapter = new MyAdapter(this);
		setListAdapter(mAdapter);
		
	}
	
}
